// package: rewords-server-2024
// filename: admin
// author: diogoxiang@gmail.com
// time: 2024/11/8 16:48

package admin

import (
	"context"

	"rewords-server-2024/api/admin"
	"rewords-server-2024/internal/consts"
	"rewords-server-2024/internal/service"

	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gconv"
	"go.mongodb.org/mongo-driver/bson"
)

var (
	App = new(cApp)
)

type cApp struct{}

func (c *cApp) AppData(ctx context.Context, req *admin.AppDataReq) (res *admin.AppDataRes, err error) {
	// Initialize response
	res = &admin.AppDataRes{}

	// Fetch config data from c_config_app collection
	configQuery := bson.M{"status": "normal"}
	configResults, err := service.Mgx().Find(ctx, consts.CConfig_app, configQuery, nil, 0, consts.DefaultLimit, nil)
	if err != nil {
		return nil, gerror.Wrap(err, "获取配置数据失败")
	}

	// Transform config results into required format
	configMap := make(map[string]any)
	for _, conf := range configResults {
		config := gconv.Map(conf)
		scope := gconv.String(config["scope"])
		if _, exists := configMap[scope]; !exists {
			configMap[scope] = make([]map[string]any, 0)
		}

		configItem := map[string]any{
			"scope": config["scope"],
			"key":   config["key"],
			"value": config["value"],
		}
		configMap[scope] = append(configMap[scope].([]map[string]any), configItem)
	}
	res.Config = configMap

	// Fetch dictionary data from c_config collection
	dictQuery := bson.M{"status": "normal", "group": bson.M{"$exists": true}}
	dictResults, err := service.Mgx().Find(ctx, consts.CConfig, dictQuery, nil, 0, consts.DefaultLimit, nil)
	if err != nil {
		return nil, gerror.Wrap(err, "获取字典数据失败")
	}

	// Transform dictionary results
	dict := make(map[string]any)
	for _, item := range dictResults {
		dictItem := gconv.Map(item)
		group := gconv.String(dictItem["group"])
		if _, exists := dict[group]; !exists {
			dict[group] = make([]map[string]any, 0)
		}

		status := map[string]any{
			"group": dictItem["group"],
			"label": dictItem["label"],
			"value": dictItem["value"],
		}
		dict[group] = append(dict[group].([]map[string]any), addGroupField(status, group))
	}
	res.Dict = dict

	return res, nil
}

// 辅助函数：添加group字段
func addGroupField(status map[string]any, group string) map[string]any {
	result := make(map[string]any)
	for k, v := range status {
		result[k] = v
	}
	result["group"] = group
	return result
}
